package com.aduerr.v1shouyin.http;


import android.text.TextUtils;
import android.util.Log;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 * @since 2017/2/13
 */

public class APIRetrofit {

    public static final String TAG = "APIRetrofit";

    /**
     * 默认超时时间 单位/秒
     */
    private static final int DEFAULT_TIME_OUT = 60;
    private static final String CER_NAME = "";   //https签名证书name
    private static Retrofit sRetrofit;
    private static OkHttpClient sOKHttpClient;

    public static APIService getAPIService() {
        return getInstance().create(APIService.class);
    }

    public static Retrofit getInstance() {
        if(sRetrofit == null) {
            synchronized(APIRetrofit.class) {
                if(sRetrofit == null) {

                    sRetrofit = new Retrofit.Builder()
                            .baseUrl(Constants.BASE_URL)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(getsOKHttpClient())
                            .build();

                }
            }
        }

        return sRetrofit;
    }

    public static OkHttpClient getsOKHttpClient() {

        if(TextUtils.isEmpty(CER_NAME)) {
            //忽略所有证书
            overlockCard();
        }
        if(sOKHttpClient == null) {
            synchronized(APIRetrofit.class) {

                if(sOKHttpClient == null) {
                    sOKHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                            .readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                            .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                            //添加网络拦截器
                            .addNetworkInterceptor(new LogInterceptor())
//                            .sslSocketFactory(sslContext.getSocketFactory())
//                            .hostnameVerifier(DO_NOT_VERIFY)
                            .build();
                }
            }
        }

        return sOKHttpClient;
    }

    /**
     * 忽略所有https证书
     */
    private static void overlockCard() {
        final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        }};
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts,
                    new java.security.SecureRandom());
        } catch(Exception e) {
            ToastUtils.showToast(App.getApp(), "ssl出现异常" + e.getMessage());
        }

    }

    /**
     * 创建日志拦截器
     * 在addNetworkInterceptor()中添加
     * 打印请求日志
     *
     * @return
     */
    static class LogInterceptor implements Interceptor {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            Log.i("OkHttp", "HttpHelper1" + String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));
            okhttp3.Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            Log.i("OkHttp", "HttpHelper2" + String.format("Received response for %s in " +
                            "%.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            okhttp3.MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            Log.i("OkHttp", "response body:" + content);
            return response.newBuilder()
                    .body(okhttp3.ResponseBody.create(mediaType, content))
                    .build();
        }
    }


}
